package chapter_23.security;

/**
 * 多线程同步(访问"临界资源")
 * (synchronized 语句)
 */
public class TicketDB2 {

    public static void main(String[] args) {

        TicketDB ticketDB = new TicketDB();

        // 创建线程 t1
        Thread t1 = new Thread(() -> {
            function(ticketDB);
        });
        // 开始线程 t1
        t1.start();

        // 创建线程 t2
        Thread t2 = new Thread(() -> {
            function(ticketDB);
        });
        // 开始线程 t1
        t2.start();
    }

    public static void function(TicketDB ticketDB) {
        while (true) {
            synchronized (ticketDB) {
                int currTicketCount = ticketDB.getTicketCount();
                // 查询是否有票
                if (currTicketCount > 0) {
                    ticketDB.sellTicket();
                } else {
                    // 无票退出
                    break;
                }
            }
        }
    }

}
